package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public PageResult<SpuBo> querySpuBo(String key, Boolean saleable, Integer page, Integer rows) {

        // 准备设置查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 根据关键字模糊查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        // 查询是否上下架的商品
        if (saleable != null ) {
            criteria.andEqualTo("saleable", saleable);
        }

        // 设置分页
        PageHelper.startPage(page, rows);

        // 执行查询
        Page<Spu> pageInfo = (Page<Spu>)this.spuMapper.selectByExample(example);

        // 获取spubo
        List<SpuBo> spuBoList = pageInfo.getResult().stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            // copyspu中的属性值给spubo对象
            BeanUtils.copyProperties(spu, spuBo);

            // 查询整个分类路径
            List<String> names = this.categoryService.queryNamesByCids(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(names, "-"));

            // 获取品牌名称
            Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());

            return spuBo;
        }).collect(Collectors.toList());

        return new PageResult<>(pageInfo.getTotal(), spuBoList);
    }

    @Transactional
    public void saveGoods(SpuBo spuBo) {

        // 保存spu信息
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuBo, spu);
        spu.setId(null);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());
        spu.setSaleable(true);
        spu.setValid(true);
        this.spuMapper.insert(spu);

        // 获取spuid，保存spuDetail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spu.getId());
        this.spuDetailMapper.insertSelective(spuDetail);
        saveSkuAndStock(spuBo, spu.getId());

        this.sendMessage(spu.getId(), "insert");
    }

    private void saveSkuAndStock(SpuBo spuBo, Long spuId) {
        // 保存skus
        List<Sku> skus = spuBo.getSkus();
        skus.forEach(sku -> {
            sku.setSpuId(spuId);
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);

            // 保存库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insertSelective(stock);
        });
    }

    @Transactional
    public void updateGoods(SpuBo spuBo) {


        // 过滤skus，将ownSPec属性不一致的进行删除新增，一致的仅进行更新，skuid是不变的，与用户商品收藏相关
        // 根据spuId查询旧的skus
        List<Sku> skus = this.querySkusBySpuId(spuBo.getId());
        // 获取新的sku集合
        List<Sku> newSkus = spuBo.getSkus();
        // 遍历新旧商品集合，过滤并更新需要更新的数据，获取需要全部删除的集合，和需要新增的集合
        // 遍历之后获得的skus为需要删除的旧的sku集合，newSkus为需要新增的新的sku集合
        for (int i = 0; i < skus.size(); i++) {
            Sku old = skus.get(i);
            for (int j = 0; j < newSkus.size(); j++) {
                Sku newSku = newSkus.get(j);
                if (StringUtils.equals(newSku.getOwnSpec(), old.getOwnSpec())) {
                    // 说明该商品并不需要删除，只需要更新
                    // id不变
                    Long skuId = old.getId();
                    newSku.setId(skuId);
                    // 其他值要重新设置
                    newSku.setSpuId(old.getSpuId());
                    newSku.setCreateTime(spuBo.getCreateTime());
                    newSku.setLastUpdateTime(spuBo.getLastUpdateTime());
                    skuMapper.updateByPrimaryKeySelective(newSku);
                    Stock stock = new Stock();
                    stock.setSkuId(skuId);
                    stock.setStock(newSku.getStock());
                    stockMapper.updateByPrimaryKey(stock);
                    // 将更新完成的sku从新旧集合中都删除掉，后面再将剩余的旧的全部删除就行了
                    skus.remove(i);
                    newSkus.remove(j);
                    i--;
                    j--;
                }
            }
        }
        // 将更新后的集合设置回去
        spuBo.setSkus(newSkus);
        List<Object> skuIds = skus.stream().map(sku->sku.getId()).collect(Collectors.toList());
        // 判断，如果skuids为空，说明旧的sku的ownspec都没有变化，不需要删除，直接跳过
        if (!CollectionUtils.isEmpty(skuIds)) {
            // 先删除旧的stock表
            Example example = new Example(Stock.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("skuId", skuIds);
            stockMapper.deleteByExample(example);
            // 删除剩余的sku
            Example example2 = new Example(Sku.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andIn("id", skuIds);
            skuMapper.deleteByExample(example2);
        }
        // 判断，如果新的skus过滤后为空，说明没有需要新增的sku，都只是需要更新，直接跳过
        // 新增
        if (!CollectionUtils.isEmpty(spuBo.getSkus())) {
            this.saveSkuAndStock(spuBo, spuBo.getId());
            // 发送更新消息
            this.sendMessage(spuBo.getId(), "update");
        }

        // 更新spudetail
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        // 更新spu
        spuBo.setSaleable(null);
        spuBo.setValid(null);
        spuBo.setCreateTime(null);
        spuBo.setLastUpdateTime(new Date());
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        this.sendMessage(spuBo.getId(), "update");
    }

    private void sendMessage(Long id, String type){
        try {
            this.amqpTemplate.convertAndSend("leyou.item.exchange", "item." + type, id);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }

    public SpuDetail queryspuDetail(Long spuId) {

        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    public List<Sku> querySkusBySpuId(Long id) {
        Sku record = new Sku();
        record.setSpuId(id);
        List<Sku> skuList = this.skuMapper.select(record);
        for (Sku sku : skuList) {
            Stock stock = this.stockMapper.selectByPrimaryKey(sku.getId());
            sku.setStock(stock.getStock());
        }
        return skuList;
    }

    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }

    public Sku querySkuById(Long id) {
        return this.skuMapper.selectByPrimaryKey(id);
    }


    public List<Sku> queySkusByIds(List<Long> skuIds) {
        return skuMapper.selectByIdList(skuIds);
    }


    public List<Spu> querySpusBySpuIds(List<Long> spuIds) {
        return spuMapper.selectByIdList(spuIds);

    }


    public void downSpuSaleableBySpuid(Long spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(false);
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    public void upSpuSaleableBySpuid(Long spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(true);
        spuMapper.updateByPrimaryKeySelective(spu);
    }
}
